import os
import json
from pathlib import Path

class ConfigManager:
    def __init__(self, app_name="RobotZL"):
        """初始化配置管理器"""
        self.app_name = app_name
        self.config_dir = self.get_appdata_path()
        
        # 确保配置目录存在
        os.makedirs(self.config_dir, exist_ok=True)
    
    def get_appdata_path(self):
        """获取AppData配置目录路径"""
        if os.name == 'nt':  # Windows
            appdata = os.environ.get('APPDATA')
            if appdata:
                return os.path.join(appdata, self.app_name)
        
        # 其他系统的备用路径
        home = Path.home()
        return os.path.join(home, f'.{self.app_name.lower()}')
    
    def get_config_path(self, filename):
        """获取配置文件的完整路径"""
        return os.path.join(self.config_dir, filename)
    
    def load_config(self, filename, default_config=None):
        """加载配置文件"""
        config_path = self.get_config_path(filename)
        
        try:
            if os.path.exists(config_path):
                with open(config_path, 'r', encoding='utf-8') as f:
                    return json.load(f)
            elif default_config is not None:
                # 如果文件不存在但有默认配置，保存默认配置
                self.save_config(filename, default_config)
                return default_config
            else:
                return {}
        except Exception as e:
            print(f"加载配置文件 {filename} 失败: {e}")
            return default_config if default_config is not None else {}
    
    def save_config(self, filename, config_data):
        """保存配置文件"""
        config_path = self.get_config_path(filename)
        
        try:
            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存配置文件 {filename} 失败: {e}")
            return False
    
    def migrate_old_config(self, old_path, new_filename):
        """迁移旧的配置文件到AppData"""
        if os.path.exists(old_path):
            try:
                with open(old_path, 'r', encoding='utf-8') as f:
                    old_config = json.load(f)
                
                # 保存到新位置
                if self.save_config(new_filename, old_config):
                    print(f"配置文件已迁移: {old_path} -> {self.get_config_path(new_filename)}")
                    # 可选：删除旧文件
                    # os.remove(old_path)
                    return True
            except Exception as e:
                print(f"迁移配置文件失败: {e}")
        return False

# 全局配置管理器实例
config_manager = ConfigManager()